/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
 */

package pl.droidsonroids.gif;

import static pl.droidsonroids.gif.InvalidationHandler.MSG_TYPE_INVALIDATION;

import ohos.miscservices.timeutility.Time;

import java.util.concurrent.TimeUnit;

/**
 * 功能描述
 *
 * @author bwx484721
 * @since 2020-07-13
 */
class RenderTask extends SafeRunnable {

	RenderTask(GifDrawable gifDrawable) {
		super(gifDrawable);
	}

	@Override
	public void doWork() {
		final long invalidationDelay = mGifDrawable.mNativeInfoHandle.renderFrame(mGifDrawable.mPixelMap);
		if (invalidationDelay >= 0) {
			mGifDrawable.mNextFrameRenderTime = Time.getRealActiveTime() + invalidationDelay;
			if (mGifDrawable.getVisible() && mGifDrawable.mIsRunning && !mGifDrawable.mIsRenderingTriggeredOnDraw) {
				mGifDrawable.mExecutor.remove(this);
				mGifDrawable.mRenderTaskSchedule = mGifDrawable.mExecutor.schedule(this, invalidationDelay,
					TimeUnit.MILLISECONDS);
			}
			if (!mGifDrawable.mListeners.isEmpty() && mGifDrawable.getCurrentFrameIndex()
				== mGifDrawable.mNativeInfoHandle.getNumberOfFrames() - 1) {
				mGifDrawable.mInvalidationHandler.sendEvent(mGifDrawable.getCurrentLoop(),
					240);//mGifDrawable.mNextFrameRenderTime);
			}
		} else {
			mGifDrawable.mNextFrameRenderTime = Long.MIN_VALUE;
			mGifDrawable.mIsRunning = false;
		}
		if (mGifDrawable.getVisible() && !mGifDrawable.mInvalidationHandler.hasInnerEvent(MSG_TYPE_INVALIDATION)) {
			mGifDrawable.mInvalidationHandler.sendEvent(MSG_TYPE_INVALIDATION, 0);
		}
	}
}
